package com.cloud.servicezuul.compoment;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

/**
 * 用springcloud alibaba 组件 sentinel 来实现令牌桶限流
 *  这个限流需要先初始化令牌桶
 *  初始化代码就写在配置类里面了  配置类：SentinelConfig
 */
@Component
@SuppressWarnings("all")
public class SentinelLimitFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return Integer.MIN_VALUE;
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }

    @Override
    public Object run() throws ZuulException {

        //已经初始化了令牌桶，现在在这里调用
        Entry entry = null;
        try {
            entry = SphU.entry("service-sms");
            //这里走正常的业务逻辑
            System.out.println("拿到令牌了，走正常的业务逻辑");

        } catch (BlockException e) {
            e.printStackTrace();
            //这里就是被限流了，走限流的业务逻辑
            System.out.println("被限流了");

        }finally {
            if (entry != null){
                entry.exit();
            }
        }

        return null;
    }
}
